<template>
  <div>
    <page-dialog
      :title="state.dialogInfo.title"
      v-model:visible="shows"
      :width="state.dialogInfo.width"
      :bt-loading="state.dialogInfo.btLoading"
      :bt-list="state.dialogInfo.btList"
    >
      <!-- 条件栏 -->
      <page-filter
        v-model:query="state.tableInfo.query"
        :filter-list="state.tableInfo.list"
      />
      <div class="select-resource-table">
        <page-table
          ref="printTemplateTable"
          :refresh="state.tableInfo.refresh"
          :init-curpage="state.tableInfo.initCurpage"
          v-model:ref-obj="state.tableInfo.ref"
          v-model:data="state.tableInfo.data"
          :api="state.api"
          :query="state.tableInfo.query"
          :listen-height="true"
          :selectable="selectable"
          :tab-index="true"
          :pager="true"
          :table-height="350"
          :field-list="state.tableInfo.fieldList"
          :handle="state.tableInfo.handle"
          :highlight-row="state.highlightRow"
          :checked-list="state.tableInfo.checkedList"
          :checked-key="state.tableInfo.checkedKey"
          :check-box="state.checkBox"
          @handleEvent="handleEvent"
        />
        <page-table
          ref="cachePrintTemplateTable"
          :init-curpage="state.cacheTableInfo.initCurpage"
          v-model:data="state.cacheTableInfo.data"
          :field-list="state.cacheTableInfo.fieldList"
          :handle="state.cacheTableInfo.handle"
          :listen-height="false"
          :table-height="350"
          :check-box="false"
          :tab-index="true"
          :pager="false"
        />
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="PrintTemplateDialog">
import PageDialog from "@/components/PageDialog/index";
import PageFilter from "@/components/PageFilter/index";
import PageTable from "@/components/PageTable/index";
import {
  insertResourcesPrintTemplate,
  fatchResourcesPrintTemplate,
} from "@/api/mapping";
import { fatchPrintTemplate, fatchPrintTemplateCode } from "@/api/base";
import _ from "lodash";

let { proxy } = getCurrentInstance();
const emit = defineEmits()

const props = defineProps({
  highlightRow: {
    type: Boolean,
    default: false,
  },
  checkBox: {
    type: Boolean,
    default: true,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {};
    },
  },
});

const state = reactive({
  api: fatchPrintTemplate,
  resourceType: "dept",
  // 表格相关
  tableInfo: {
    refresh: 1,
    ref: {},
    initCurpage: 1,
    data: [],
    checkedList: [],
    checkedKey: "id",
    query: {
      name: "",
    },
    list: [
      {
        type: "input",
        label: "模板名称",
        value: "nameLike",
        event: search,
      },
      { type: "button", label: "搜索", event: search },
    ],
    fieldList: [{ label: "模板名称", value: "name" }],
  },
  cacheTableInfo: {
    refresh: 1,
    ref: {},
    initCurpage: 1,
    data: [],
    fieldList: [{ label: "模板名称", value: "name" }],
    handle: {
      label: "操作",
      width: '100',
      btList: [
        {
          label: "设为默认",
          event: onDefault,
          show: true,
          ifRender: function (row) {
            return !row.isDefault;
          },
        },
      ],
    },
  },
  // 弹窗相关
  dialogInfo: {
    title: "选择打印模板",
    btLoading: false,
    btList: [
      { label: "关闭", event: handleClose, show: true },
      {
        label: "保存",
        type: "primary",
        // disabled: true,
        event: save,
        show: true,
      },
    ],
  },
});

const shows = computed({
  get() {
    return props.showDialog;
  },
  set(newValue) {
    emit("update:showDialog", newValue);
  },
});

watch(
  () => props.showDialog,
  (val) => {
    if (val) {
      proxy.$nextTick(() => {
        getCacheList();
        getList();
      });
    }
  },
  {
    immediate: true,
  }
);
watch(
  () => state.tableInfo.data,
  (val) => {
    if (val.length) {
      proxy.$nextTick(() => {
        val.forEach((item, index) => {
          let findex = state.cacheTableInfo.data.findIndex(
            (it) => it.id === item.id
          );
          if (findex !== -1) {
            proxy.$refs["printTemplateTable"].toggleRowSelection(
              item
            );
            proxy.$refs["printTemplateTable"].tableData[
              index
            ]._checked = true;
          }

          if (item.disabled) {
            proxy.$refs["printTemplateTable"].toggleRowSelection(
              item
            );
          }
        });
      });
    }
  },
  {
    immediate: true,
  }
);

onMounted(() => {
  getCacheList();
  proxy.$nextTick(() => {
    getList();
  });
});

// 获取列表
function getList () {
  state.tableInfo.refresh = Math.random();
};
// 搜索
function search () {
  // 重置分页
  state.tableInfo.initCurpage = Math.random();
  state.tableInfo.refresh = Math.random();
};
function getCacheList () {
  if (!props.query.id) {
    return;
  }
  let params = {
    resourceId: props.query.id,
  };
  fatchResourcesPrintTemplate(params).then((res) => {
    if (res && res.success) {
      let data = res.data.map((it) => {
        return {
          ...it,
          id: it.templateId,
          isDefault: Boolean(it.isDefault),
          _checked: true,
        };
      });
      state.cacheTableInfo.data = [...data];
    }
  });
};
function onDefault (row) {
  const findDefaultValue = state.cacheTableInfo.data.find(
    (item) => item.isDefault
  );

  if (findDefaultValue) findDefaultValue.isDefault = false;

  state.cacheTableInfo.data.map((item, index) => {
    if (findDefaultValue && item.id === findDefaultValue.id) {
      state.cacheTableInfo.data[index] = {
        ...state.cacheTableInfo.data[index],
        isDefault: false,
      }
    }
    if (item.id === row.id) {
      state.cacheTableInfo.data[index] = {
        ...state.cacheTableInfo.data[index],
        isDefault: true,
      }
    }
  });
};
function cacheRemove (row, index) {
  const rows = state.cacheTableInfo.data;
  rows.splice(index, 1);
  if (rows) {
    state.tableInfo.checkedList = rows.map((item) =>
    state.tableInfo.checkedList[index] = item.id
    );
  } else {
    state.tableInfo.checkedList = [];
  }

  handleEvent("tableCheck", rows);
};
function save () {
  if (state.cacheTableInfo.data.length) {
    let params = state.cacheTableInfo.data.map((it) => {
      return {
        isDefault: Number(!!it.isDefault),
        resourceId: Number(props.query.id),
        templateId: it.id,
      };
    });
    insertResourcesPrintTemplate(params).then((res) => {
      if (res && res.success) {
        handleClose();
      }
    });
  } else {
    proxy.$message({
      type: "warning",
      duration: 3500,
      showClose: true,
      message: "请选择打印模板",
    });
  }
};
function handleEvent (event, data, mainData, row) {
  if (event === "selectCheck") {
    let cacheTableData = [...state.cacheTableInfo.data];
    let _data = _.unionBy([...cacheTableData, ...data], "id");

    if (row && !row._checked) {
      // 单选取消
      _data = _.remove(_data, (n) => {
        return n.id !== row.id;
      });
    }

    let _checkedData = _.filter(_data, ["_checked", true]);
    let hasDefault = _.some(_checkedData, ["isDefault", true]);
    if (!hasDefault) {
      if (_checkedData.length) {
        _checkedData[0].isDefault = true;
      }
    }

    state.cacheTableInfo.data = [..._checkedData];
    state.tableInfo.checkedList = [..._checkedData];
    state.tableInfo.data = [...mainData];
    state.dialogInfo.btList[1].disabled = !Object.keys(_checkedData).length;
  }
};
// 关闭弹窗前的回调
function handleClose () {
  shows.value = false;
  emit("reset");
};
function selectable (row, index) {
  if (row.disabled) {
    return false;
  }
  return true;
};
</script>

<style scoped lang="scss">
.page-table {
  width: 48%;
  height: 400px;
  .el-dialog__body {
    display: flex;
    flex-direction: column;
  }
}
.el-table--border {
  border-bottom: 1px solid #ebeef5;
}
.select-resource-table {
  display: flex;
  flex-flow: row;
  justify-content: space-between;
  // overflow: hidden;
  height: 400px;
}
</style>
